package src.main.java.com.pms.gui.dialog.stats;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.ResultSet;
import src.main.java.com.pms.service.PetStatisticsService;

public class AgeStatsDialog extends JDialog {
    private JTable statsTable;
    private DefaultTableModel tableModel;
    private PetStatisticsService statsService;

    public AgeStatsDialog(JFrame parent) {
        super(parent, "宠物年龄统计", true);
        statsService = new PetStatisticsService();
        initComponents();
        loadAgeStats();
    }

    private void initComponents() {
        setSize(600, 400);
        setLocationRelativeTo(getParent());

        // 创建表格模型
        String[] columnNames = {"年龄段", "数量"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        statsTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(statsTable);

        // 设置布局
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
    }

    private void loadAgeStats() {
        try {
            // 清空表格
            tableModel.setRowCount(0);
            
            // 获取年龄统计数据
            ResultSet rs = statsService.countPetsByAgeRange();
            while (rs.next()) {
                Object[] row = {
                    rs.getString("age_range"),
                    rs.getInt("count")
                };
                tableModel.addRow(row);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载数据失败：" + e.getMessage(), 
                "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
